/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.mzk.oai.metadataRepository.metadata;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author Martin Rehanek, Martin.Rehanek@gmail.com
 */
public class RepeatableDataField {

    List<DataField> dataFields;

    public RepeatableDataField(int initialCapacity) {
        dataFields = new ArrayList<DataField>(initialCapacity);
    }

    public void addDataField(DataField datafield) {
        dataFields.add(datafield);
    }

    /**
     *
     * @param subfieldCode
     * @return List of contents of subfields with code from all datafields
     */
    public List<String> getSubfieldContents(char subfieldCode) {
        List<String> subfields = new ArrayList<String>();
        for (DataField datafield : dataFields) {
            String subfield = datafield.getSubfield(subfieldCode);
            if (subfield != null) {
                subfields.add(subfield);
            }
        }
        return subfields;
    }

    public boolean hasDatafieldWithSubfieldValue(char subfieldCode, String value) {
        return hasDatafieldWithSubfieldValue(subfieldCode, value, false);
    }

    /**
     * Returns true if there exists at least one datafield with its subfield
     * $subfieldCode containing $value
     *
     * @param value Value of the subfield $code we are looking for
     * @param subfieldCode Code of the subfield
     * @param caseSensitive whether comparision of subfield content should be
     * case sensitive
     * @return true if there exists a subfield (in one of datafields), content
     * of which equals $value (it is case in sensitive)
     */
    public boolean hasDatafieldWithSubfieldValue(char subfieldCode, String value, boolean caseSensitive) {
        List<String> subfields = getSubfieldContents(subfieldCode);
        for (String subfield : subfields) {
            if (caseSensitive) {
                if (value.equals(subfield)) {
                    return true;
                }
            } else {
                if (subfield.toLowerCase().equals(value.toLowerCase())) {
                    return true;
                }
            }
        }
        return false;
    }

    public int numberOfDatafields() {
        return dataFields.size();
    }

    public boolean empty() {
        return 0 == numberOfDatafields();
    }

    /**
     *
     * @param subfieldCode
     * @return values of given subfield of this datafield
     */
    public String toString(char subfieldCode) {
        List<String> subfields = getSubfieldContents(subfieldCode);
        StringBuilder builder = new StringBuilder(2);
        for (int i = 0; i < subfields.size(); i++) {
            builder.append(subfields.get(i));
            if (i != subfields.size() - 1) {
                builder.append(':');
            }
        }
        return builder.toString();
    }
}
